import cv2
from PySide6.QtCore import QTimer, Signal, QObject, Qt
from PySide6.QtWidgets import QWidget, QLabel, QVBoxLayout, QPushButton

class CameraManager(QObject):
    release_countdown = Signal(int)  # 剩余时间通知
    released = Signal()              # 真正释放完成时通知

    def __init__(self, delay_release_time=5):
        super().__init__()
        self.cap = None
        self.initialized = False
        self.release_delay = delay_release_time
        self._release_timer = QTimer()
        self._release_timer.timeout.connect(self._on_release_timer)
        self.remaining_time = delay_release_time

    def initialize_camera(self):
        if not self.initialized:
            self.cap = cv2.VideoCapture(0)
            if not self.cap.isOpened():
                print("摄像头无法打开")
                return
            print("摄像头初始化完成")
            self.initialized = True

    def get_frame(self):
        if self.cap and self.cap.isOpened():
            ret, frame = self.cap.read()
            return frame if ret else None
        return None

    def start_release_countdown(self):
        self.remaining_time = self.release_delay
        self._release_timer.start(1000)

    def _on_release_timer(self):
        self.remaining_time -= 1
        self.release_countdown.emit(self.remaining_time)
        if self.remaining_time <= 0:
            self._release_timer.stop()
            self._release_camera()

    def _release_camera(self):
        if self.cap and self.cap.isOpened():
            self.cap.release()
            self.initialized = False
            print("摄像头已释放")
            self.released.emit()


class ScanWidget(QWidget):
    def __init__(self, camera_manager: CameraManager):
        super().__init__()
        self.camera_manager = camera_manager
        self.camera_manager.initialize_camera()
        self.init_ui()

    def init_ui(self):
        self.label = QLabel("扫码区域")
        self.info_label = QLabel("")
        self.close_button = QPushButton("关闭")

        layout = QVBoxLayout()
        layout.addWidget(self.label)
        layout.addWidget(self.info_label)
        layout.addWidget(self.close_button)
        self.setLayout(layout)

        self.close_button.clicked.connect(self.close)

        self.camera_manager.release_countdown.connect(self.update_countdown_label)
        self.camera_manager.released.connect(lambda: self.info_label.setText("摄像头已释放"))

    def closeEvent(self, event):
        self.info_label.setText(f"将在 {self.camera_manager.release_delay} 秒后释放摄像头")
        self.camera_manager.start_release_countdown()
        event.accept()

    def update_countdown_label(self, seconds_left):
        self.info_label.setText(f"摄像头将在 {seconds_left} 秒后释放")


# 主程序入口
if __name__ == "__main__":
    import sys
    from PySide6.QtWidgets import QApplication

    app = QApplication(sys.argv)
    cam_manager = CameraManager(delay_release_time=5)
    widget = ScanWidget(cam_manager)
    widget.show()
    sys.exit(app.exec())
